import axios from 'axios'
import Vue from 'vue'

Vue.prototype.$ajax = axios
axios.defaults.timeout = 10000
axios.defaults.retry = 4
axios.defaults.retryDelay = 1000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.withCredentials = true

// 请求
axios.interceptors.request.use(function (config) {
  if (config.method === 'post' || config.method === 'put') {
    axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
  } else {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  }

  return config
}, function (error) {
  alert('加载超时')
  return Promise.reject(error)
})

// 响应
axios.interceptors.response.use(function (res) {
  return res.data
}, function (error) {
  var config = error.config
  if (!config || !config.retry) return Promise.reject(error)
  config.__retryCount = config.__retryCount || 0
  if (config.__retryCount >= config.retry) {
    // Reject with the error
    alert('当前网络不稳定，请稍后再试！')
    return Promise.reject(error)
  }
  config.__retryCount += 1
  var backoff = new Promise(function (resolve) {
    setTimeout(function () {
      resolve()
    }, config.retryDelay || 1)
  })
  return backoff.then(function () {
    return axios(config)
  })
})
